<template>
    <view
        class="continer overflow-hidden text-muted"
        :style="{ 'font-size': fontSize }"
        :class="{ boxNExpand: showExpandBtn, boxEexpand: !showExpandBtn }"
    >
        <text class="expandBtn" :style="{ color: btnColor }" @click="expand" v-if="showExpandBtn">
            展开
        </text>
        <text class="content overflow-hidden">{{ content }}</text>
        <text class="upBtn" :style="{ color: btnColor }" v-if="showUpBtn" @click="up">收起</text>
    </view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { getCurrentInstance, reactive, ref, watch } from 'vue'
import type { IcssParams } from './interface'
import { getRPX } from '../../utils/util'

const props = defineProps({
    content: {
        type: String,
        default: ''
    },
    lineHeight: {
        type: Number,
        default: 44
    },
    //几行打点
    row: {
        type: Number,
        default: 3
    },
    fontSize: {
        type: String,
        default: '44rpx'
    },
    btnColor: {
        type: String,
        default: '#456456'
    }
})
//展开按钮 显示/隐藏
const showExpandBtn = ref<boolean>(true)
//收起按钮 显示/隐藏
const showUpBtn = ref<boolean>(false)
//实际行数
let realRow = 0
//css参数
const cssParams: IcssParams = reactive({
    lineHight: '44rpx',
    row: 3,
    boxHeight: '132rpx',
    boxBeforH: '88rpx'
})

watch(
    () => props,
    (value: any) => {
        cssParams.lineHight = value.lineHeight + 'rpx'
        cssParams.row = value.row
        cssParams.boxHeight = value.lineHeight * value.row + 'rpx'
        cssParams.boxBeforH = value.lineHeight * (value.row - 1) + 'rpx'
    },
    { immediate: true }
)

//展开
const expand = () => {
    showExpandBtn.value = false
    showUpBtn.value = true
}
//收起
const up = () => {
    showExpandBtn.value = true
    showUpBtn.value = false
}

const instance = getCurrentInstance() // 获取组件实例

onShow(() => {
    setTimeout(() => {
        const text = uni.createSelectorQuery().in(instance).select('.content')
        text.boundingClientRect((value: any) => {
            realRow = Math.floor(getRPX(value.height) / props.lineHeight)
            showExpandBtn.value = realRow > props.row ? true : false
        }).exec()
    }, 500)
})
</script>

<style scoped lang="scss">
.boxNExpand {
    line-height: v-bind('cssParams.lineHight');
    // height: v-bind('cssParams.boxHeight');
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: v-bind('cssParams.row');
    -webkit-box-orient: vertical;

    &::before {
        content: '';
        float: right;
        width: 0rpx;
        height: v-bind('cssParams.boxBeforH');
        background: #000;
    }
}

.boxEexpand {
    line-height: v-bind('cssParams.lineHight');
    overflow: visible;
}

.expandBtn {
    float: right;
    clear: both;
}
</style>
